package main

import (
	"net/http"
	"time"
	"os"
	"os/signal"
	"syscall"
	"fmt"
	"github.com/gin-gonic/gin"
	"context"
	"strconv"
)

func SlowHandler(c *gin.Context) {
	fmt.Println("[start] SlowHandler")
	//time.Sleep(30 * time.Second)
	time.Sleep(10 * time.Second)
	fmt.Println("[end] SlowHandler")
	c.JSON(http.StatusOK, gin.H{

		"message": "success",
	})
}

func HomeHandler(c *gin.Context) {
        client := &http.Client{Timeout: 10*time.Second}
        url := "http://127.0.0.1:30000/foo" 
        req, _ := http.NewRequest("GET", url, nil)
        _, _ = client.Do(req)
        //if err != nil {
        //   fmt.Println(err)
        //    c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        //    return
      //  }
	c.JSON(http.StatusOK, gin.H{

		"message": time.Unix(time.Now().Unix(), 0,).Format("2006-01-02 15:04:05"),
	})
}

func main() {
	r := gin.Default()
	// 1.
	r.GET("/", HomeHandler)
	r.GET("/slow", SlowHandler)


	server := &http.Server{
		Addr:           ":9090",
		Handler:        r,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go server.ListenAndServe()

	//将pid写入文件
	f, err := os.Create("/tmp/app-demo.pid")
	defer f.Close()
	if err != nil{
		fmt.Println(err.Error())
	}else{
		_,err = f.Write([]byte(strconv.Itoa(syscall.Getpid())+"\n"))

	}
	// 设置优雅退出
	gracefulExitWeb(server)
}

func gracefulExitWeb(server *http.Server) {
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)
	sig := <-ch

	fmt.Println("got a signal", sig)
	now := time.Now()
	cxt, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	err := server.Shutdown(cxt)
	if err != nil {
		fmt.Println("err", err)
	}

	// 看看实际退出所耗费的时间
	fmt.Println("------exited--------", time.Since(now))
}

